package com.yh.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.net.URLEncoder;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.yh.domain.User;
import com.yh.service.IExcelService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @author yh
 * @date 2021-4-4
 */
@RestController
@RequestMapping("/file")
@AllArgsConstructor
public class FileController {
    private final IExcelService excelService;

    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<User> users = excelService.exportExcel();
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.merge(4, "用户");
        writer.write(users, true);
        String fileName = URLEncoder.createDefault().encode("用户数据", Charset.forName("UTF-8"));
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @PostMapping("/importExcel")
    public void importExcel(@RequestParam(required = false,value = "file") MultipartFile file) {
        excelService.importExcel(file);
    }
}
